public class NQueens {
    private static int N = 4;
    private static int id = 0;
    private static int[][] arr = new int[N][N];

    public static void main(String[] args) {
        nQueens(0);
    }

    private static void nQueens(int row) {
        if (row == N) {
            id++;
            System.out.println("第" + id + "种解:");
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < N; j++) {
                    System.out.print(arr[i][j] + " ");
                }
                System.out.println();
            }
        } else {
            for (int col = 0; col < N; col++) {
                if (check(row, col)) {
                    arr[row][col] = 1;
                    nQueens(row + 1);
                    arr[row][col] = 0;
                }
            }
        }
    }

    private static boolean check(int row, int col) {
        //正上
        for (int r = row - 1; r >= 0; r--) {
            if (arr[r][col] == 1) {
                return false;
            }
        }

        //左上
        for (int r = row - 1, c = col - 1; r >= 0 && c >= 0; r--, c--) {
            if (arr[r][c] == 1) {
                return false;
            }
        }

        //右上
        for (int r = row - 1,c = col + 1; r >= 0 && c < N; r--, c++) {
            if (arr[r][c] == 1) {
                return false;
            }
        }
        return true;
    }
}